import axios from "axios";
import store from "@/store";
import { getToken } from "@/utils/auth";

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  withCredentials: true,
  responseType: "blob"
});
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers["Content-Type"] = "application/json;charset=UTF-8";
      config.headers["token"] = getToken();
    }
    return config;
  },
  error => Promise.reject(error)
);

service.interceptors.response.use(response => {
  const blob = new Blob([response.data]);
  const name = headerName(response);
  download(blob, name);
  return response;
});

function headerName(response) {
  const disposition = response.headers["content-disposition"];
  return (
    disposition.slice(disposition.lastIndexOf("filename") + 9).trim() ||
    "未命名.txt"
  );
}

function download(blob, name) {
  const linkNode = document.createElement("a");
  linkNode.style.display = "none";
  linkNode.href = URL.createObjectURL(blob);
  linkNode.download = name;
  document.body.appendChild(linkNode);
  linkNode.click();
  URL.revokeObjectURL(linkNode.href);
  document.body.removeChild(linkNode);
}

export default service;
